package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.database.GetBySqlMapper;
import com.gistone.commis.dto.*;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.*;
import com.gistone.commis.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.*;

import freemarker.template.Template;

/**
 * Created by wangfan on 2017/5/20.
 */
@RestController("apiFundController")
@RequestMapping("api/fund")
public class FundController {

    private static final Logger logger = LoggerFactory.getLogger(FundController.class);
    @Autowired
    private GetBySqlMapper getBySqlMapper;
    @Autowired
    CommunityInfoMapper communityInfoMapper;

    @Autowired
    private FundMapper fundMapper;


    @Autowired
    private FundChangeMapper fundChangeMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private DepartMapper departMapper;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
//	private Base64 b64Encoder = new Base64();

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/muticreate")
    public Result muticreate(HttpServletRequest request, HttpServletResponse response, Fund fund) {
        Date date = new Date();
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        fund.setUserId(user.getUserId());
        fund.setPersonName(user.getRealName());
        fund.setRegisterTime(date);


        try {
            if (null == fund.getCommunityId()) {
                fund.setCommunityId(user.getCommunityId());
            }
            fund.setIsOff(0);

            if (null == fund.getSubmitNumber()) {
                fund.setSubmitNumber(1);
            }

            if (null == fund.getDepartId()) {
                fund.setDepartId(user.getDepartId());
            }
            fund.setBigAmount( NumberToCN.number2CNMontrayUnit(new BigDecimal(fund.getAmount())));


            if (fundMapper.insertSelective(fund) > 0) {


                FundChange fundChange = new FundChange();
                fundChange.setPpId(fund.getPpId());
                fundChange.setCurrentState(AuditState.WATING);
                fundChange.setCurrentAuditorId(user.getUserId());
                fundChange.setLastAuditorId(user.getUserId());
                fundChange.setCurrentDatetime(date);
                fundChange.setLastDatetime(date);
                fundChange.setAmount(fund.getAmount());
                fundChange.setSubmitNumber(fund.getSubmitNumber());
                fundChange.setIsValid(false);


                if (fundChangeMapper.insert(fundChange) > 0) {
                    logger.info("保存群众经费信息成功");
                } else {
                    logger.info("保存群众经费信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }
            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        } catch (NumberFormatException e) {
            return new Result(Status.ERROR, "", "");
        }


        return new Result("成功");

    }

    @RequestMapping("/download/{id}")
    public void download(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        Fund f = fundMapper.selectByPrimaryKey(id);
        if (f.getIsOff() == 1) {
            response.setHeader("content-Type", "application/msword");
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
            // 下载文件的默认名称
            String filename = "fund" + id + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            freeMarkerConfigurer.getConfiguration().setClassForTemplateLoading(getClass(), "/");
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("fundImg.ftl");
            template.setEncoding("utf-8");
            String webapp = request.getServletContext().getRealPath("/");

            Map<String, Object> root = new HashMap<String, Object>();


            if (null == f.getPpName() || f.getPpName().isEmpty()) {
                root.put("ppName", "");
            } else {
                root.put("ppName", f.getPpName());
            }

            if (null == f.getPpAdd() || f.getPpAdd().isEmpty()) {
                root.put("ppAdd", "");
            } else {
                root.put("ppAdd", f.getPpAdd());
            }


            if (null == f.getAmount()) {
                root.put("amount", "");
            } else {
                root.put("amount", f.getAmount());
            }


            if (null == f.getEventsOrg() || f.getEventsOrg().isEmpty()) {
                root.put("eventsOrg", "");
            } else {
                root.put("eventsOrg", f.getEventsOrg());
            }


            if (null == f.getPeople() || f.getPeople().isEmpty()) {
                root.put("people", "");
            } else {
                root.put("people", f.getPeople());
            }
            if (null == f.getBudger() || f.getBudger().isEmpty()) {
                root.put("budger", "");
            } else {
                root.put("budger", f.getBudger());
            }
            String d = DateUtil.DATEtoString(f.getPpDate(), "yyyy-MM-dd");
            root.put("ppDate", d);
            String detail = f.getPpDetail();
            if (null == detail || detail.isEmpty()) {
                root.put("ppDetail", "");
            } else {


                root.put("ppDetail", f.getPpDetail().replaceAll("\n", "</w:t></w:r></w:p><w:p w14:paraId=\"6A3E2D5B\" w14:textId=\"4BDB3534\" w:rsidR=\"00336BA0\" w:rsidRPr=\"00D65D0F\" w:rsidRDefault=\"00336BA0\" w:rsidP=\"008E72AA\"><w:pPr><w:autoSpaceDE w:val=\"0\"/><w:autoSpaceDN w:val=\"0\"/><w:adjustRightInd w:val=\"0\"/><w:rPr><w:rFonts w:ascii=\"宋体\" w:hAnsi=\"宋体\" w:cs=\"宋体\" w:hint=\"eastAsia\"/><w:color w:val=\"000000\"/><w:kern w:val=\"0\"/><w:sz w:val=\"28\"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii=\"宋体\" w:hAnsi=\"宋体\" w:cs=\"宋体\" w:hint=\"eastAsia\"/><w:color w:val=\"000000\"/><w:kern w:val=\"0\"/><w:sz w:val=\"24\"/></w:rPr><w:t>"));

            }
            root.put("guanpianDate", "    年  月  日");
            root.put("kezhangDate", "    年  月  日");
            root.put("zuguanDate", "    年  月  日");
            root.put("zhurenDate", "    年  月  日");

            root.put("guanpianSuggest", "");
            root.put("kezhangSuggest", "");
            root.put("zuguanSuggest", "");
            root.put("zhurenSuggest", "");

            root.put("gaizhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/blankImg/yinzhangBlank.png").getAbsolutePath()));
            root.put("juweihuiImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/blankImg/juweihuiBlank.png").getAbsolutePath()));
            root.put("guanpianImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));
            root.put("kezhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));
            root.put("zuguanImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));
            root.put("zhurenImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/signBlank.png").getAbsolutePath()));


            root.put("year", f.getNian());
            root.put("hao", f.getHao());


            root.put("bigAmount", NumberToCN.number2CNMontrayUnit(new BigDecimal(f.getAmount())));

            root.put("jwhDate", DateUtil.DATEtoString(f.getRegisterTime(),"yyyy年MM月dd日"));

            CommunityInfo ci = new CommunityInfo();
            ci.setCommunityId(f.getCommunityId());
            List<CommunityInfo> list = communityInfoMapper.selectSelective(ci);
            if (list.size() > 0) {
                CommunityInfo communityInfo = list.get(list.size() - 1);
                root.put("gaizhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/comImg/" + communityInfo.getReserveB()).getAbsolutePath()));
                root.put("juweihuiImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + communityInfo.getReserveA()).getAbsolutePath()));


            }


            String sql = "select tb_pp_change.*,tb_user.image,tb_user.user_type_id from tb_pp_change,tb_user where   tb_user.user_id =tb_pp_change.current_auditor_id " +
                    "AND  tb_pp_change.pp_id =" + "'" + f.getPpId() + "'";
            List<Map> data = new ArrayList<>();
            List<Map> results = this.getBySqlMapper.findRecords(sql);
            for (Map result : results) {
                Integer userTypeId = (Integer) result.get("user_type_id");
                if (userTypeId == 6) {
                    root.put("guanpianDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

                    root.put("guanpianImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));
                    if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
                        root.put("guanpianSuggest", "");
                    } else {
                        root.put("guanpianSuggest", result.get("suggest").toString());
                    }

                    data.add(result);
                }
                if (userTypeId == 7) {
                    root.put("kezhangDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

                    root.put("kezhangImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));
                    if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
                        root.put("kezhangSuggest", "");
                    } else {
                        root.put("kezhangSuggest", result.get("suggest").toString());
                    }
                }
                if (userTypeId == 8) {
                    root.put("zuguanDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

                    root.put("zuguanImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));
                    if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
                        root.put("zuguanSuggest", "");
                    } else {
                        root.put("zuguanSuggest", result.get("suggest").toString());
                    }
                }
                if (userTypeId == 9) {
                    root.put("zhurenDate", DateUtil.DATEtoString((Date)result.get("current_datetime"),"yyyy年MM月dd日"));

                    root.put("zhurenImg", ImageUtil.getImageString(ResourceUtils.getFile("classpath:META-INF/resources/signImg/" + result.get("image").toString()).getAbsolutePath()));
                    if (null == result.get("suggest") || result.get("suggest").toString().isEmpty()) {
                        root.put("zhurenSuggest", "");
                    } else {
                        root.put("zhurenSuggest", result.get("suggest").toString());
                    }
                }

            }


//		root.put("gaizhang", ImageUtil.getImageString(ResourceUtils.getFile("classpath:yinzhang.png").getAbsolutePath()));

//		List<User> list = userRepository.findAll();
//		for (int i = 0; i < list.size(); i++) {
//			User user = list.get(i);
//			File file = new File(webapp, user.getHeadPortrait());
//			FileInputStream fis = new FileInputStream(file);
//			byte[] imgData = new byte[fis.available()];
//			fis.read(imgData);
//			fis.close();
//			String headPortrait = b64Encoder.encodeAsString(imgData);
//			user.setHeadPortrait(headPortrait);
//		}

//		root.put("list", list);
            template.process(root, new OutputStreamWriter(response.getOutputStream(), "utf-8"));

        }
    }


/*
    @RequestMapping("/download/{id}")
	public void download(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/msword");
		// 下载文件的默认名称
		String filename = "fund"+id+".doc";
		response.setHeader("Content-Disposition", "attachment;filename="+filename);
		freeMarkerConfigurer.getConfiguration().setClassForTemplateLoading(getClass(), "/");
		Template template = freeMarkerConfigurer.getConfiguration().getTemplate("fund.ftl");

		String webapp = request.getServletContext().getRealPath("/");
		Fund f = fundMapper.selectByPrimaryKey(id);
		Map<String, Object> root = new HashMap<String, Object>();

		if(null==f.getPpName()||f.getPpName().isEmpty()) {
			root.put("ppName","");
		}else{
			root.put("ppName",f.getPpName());
		}

		if(null==f.getPpAdd()||f.getPpAdd().isEmpty()) {
			root.put("ppAdd","");
		}else{
			root.put("ppAdd",f.getPpAdd());
		}


		if(null==f.getAmount()) {
			root.put("amount","");
		}else{
			root.put("amount",f.getAmount());
		}




		if(null==f.getEventsOrg()||f.getEventsOrg().isEmpty()) {
			root.put("eventsOrg","");
		}else{
			root.put("eventsOrg",f.getEventsOrg());
		}



		if(null==f.getPeople()||f.getPeople().isEmpty()) {
			root.put("people","");
		}else{
			root.put("people",f.getPeople());
		}
		if(null==f.getBudger()||f.getBudger().isEmpty()) {
			root.put("budger","");
		}else{
			root.put("budger",f.getBudger());
		}
		String d =DateUtil.DATEtoString(f.getPpDate(),"yyyy-MM-dd");
		root.put("ppDate",d);
		String detail=f.getPpDetail();
		if(null==detail||detail.isEmpty()) {
			root.put("ppDetail","");
		}else {


			detail = detail.substring(0, detail.length() - 4);
			System.out.println(detail);
			root.put("ppDetail", f.getPpDetail().replaceAll("<p>", "").replaceAll("</p>", "</w:t></w:r></w:p><w:p w14:paraId=\"6A3E2D5B\" w14:textId=\"4BDB3534\" w:rsidR=\"00336BA0\" w:rsidRPr=\"00D65D0F\" w:rsidRDefault=\"00336BA0\" w:rsidP=\"008E72AA\"><w:pPr><w:autoSpaceDE w:val=\"0\"/><w:autoSpaceDN w:val=\"0\"/><w:adjustRightInd w:val=\"0\"/><w:rPr><w:rFonts w:ascii=\"宋体\" w:hAnsi=\"宋体\" w:cs=\"宋体\" w:hint=\"eastAsia\"/><w:color w:val=\"000000\"/><w:kern w:val=\"0\"/><w:sz w:val=\"28\"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii=\"宋体\" w:hAnsi=\"宋体\" w:cs=\"宋体\" w:hint=\"eastAsia\"/><w:color w:val=\"000000\"/><w:kern w:val=\"0\"/><w:sz w:val=\"28\"/></w:rPr><w:t>"));

		}




//		List<User> list = userRepository.findAll();
//		for (int i = 0; i < list.size(); i++) {
//			User user = list.get(i);
//			File file = new File(webapp, user.getHeadPortrait());
//			FileInputStream fis = new FileInputStream(file);
//			byte[] imgData = new byte[fis.available()];
//			fis.read(imgData);
//			fis.close();
//			String headPortrait = b64Encoder.encodeAsString(imgData);
//			user.setHeadPortrait(headPortrait);
//		}

//		root.put("list", list);
		template.process(root, new OutputStreamWriter(response.getOutputStream()));
	}
*/

    /**
     * 根据id获取项目信息
     *
     * @param id
     * @return
     */

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public Fund fund(@PathVariable int id) {
        Fund fund = fundMapper.selectByPrimaryKey(id);
        return fund;
    }

    /**
     * 新建项目信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public EditorResult<Fund> create(HttpServletRequest request, HttpServletResponse response) {
        Fund fund = new Fund();
        Date date = new Date();
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        fund.setUserId(user.getUserId());
        fund.setPersonName(user.getRealName());
        fund.setRegisterTime(date);
        EditorResult<Fund> fundEditorResult = new EditorResult<>();
        List<FieldError> fieldErrorList = new ArrayList<>();
        getFund(request, "data[0][", fund, fieldErrorList);
        if (null == fund.getCommunityId()) {
            fund.setCommunityId(user.getCommunity().getCommunityId());
        }
        fund.setIsOff(0);
        fund.setSubmitNumber(1);
        if (null == fund.getDepartId()) {
            fund.setDepartId(1);
        }


        if (fieldErrorList.size() > 0) {
            logger.error("字段格式错误");
            fundEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return fundEditorResult;
        }
        if (fundMapper.insertSelective(fund) > 0) {
            List<Fund> data = new ArrayList<>();
            data.add(fundMapper.selectByPrimaryKey(fund.getPpId()));
            fundEditorResult.setData(data);

            FundChange fundChange = new FundChange();
            fundChange.setPpId(fund.getPpId());
            fundChange.setCurrentState(AuditState.WATING);
            fundChange.setCurrentDatetime(date);
            fundChange.setCurrentAuditorId(user.getUserId());
            fundChange.setLastAuditorId(user.getUserId());
            fundChange.setLastDatetime(date);
            fundChange.setSubmitNumber(fund.getSubmitNumber());

            fundChange.setIsValid(false);


            if (fundChangeMapper.insert(fundChange) > 0) {
                logger.info("保存项目信息成功");
            } else {
                logger.info("保存项目信息失败");
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

            }
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return fundEditorResult;

    }

    /**
     * 批量修改项目信息， id以,号分割
     *
     * @param houseIdStr
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String[] arr = houseIdStr.split(",");
        EditorResult<Fund> fundEditorResult = new EditorResult<>();
        List<Fund> data = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            int fundId = Integer.valueOf(arr[i]);
            Fund fund = new Fund();
            fund.setPpId(fundId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            fund.setUserId(user.getUserId());
            getFund(request, "data[" + fundId + "][", fund, fieldErrorList);
            if (fieldErrorList.size() > 0) {
                logger.error("字段错误");
                fundEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return fundEditorResult;
            }
            Fund f = fundMapper.selectByPrimaryKey(fundId);
            int lastSubmitNO = f.getSubmitNumber();
            int currentSubmitNO = fund.getSubmitNumber();
            if (fundMapper.updateByPrimaryKeySelective(fund) > 0) {
                f = fundMapper.selectByPrimaryKey(fundId);
                data.add(f);
                FundChange fundChange;
                if (f.getIsDelete() == 0) {
                    if (lastSubmitNO == currentSubmitNO && user.getUserTypeId() == 1) {//更改信息
                        fundChange = new FundChange();
                        fundChange.setPpId(f.getPpId());
                        fundChange.setCurrentState(AuditState.Edit);
                        fundChange.setCurrentAuditorId(user.getUserId());
                        fundChange.setLastAuditorId(user.getUserId());
//						fundChange.setLastDatetime(fund.);
                        fundChange.setCurrentDatetime(new Date());
                        fundChange.setSubmitNumber(fund.getSubmitNumber());

                        fundChange.setIsValid(true);
                    } else {//重新提交
                        fundChange = new FundChange();
                        fundChange.setPpId(f.getPpId());
                        fundChange.setCurrentState(AuditState.RESUBMIT);
                        fundChange.setCurrentAuditorId(user.getUserId());
                        fundChange.setLastAuditorId(user.getUserId());
//						fundChange.setLastDatetime(fund.);
                        fundChange.setCurrentDatetime(new Date());
                        fundChange.setSubmitNumber(fund.getSubmitNumber());

                        fundChange.setIsValid(false);
                    }
                } else {

                    fundChange = new FundChange();
                    fundChange.setPpId(f.getPpId());
                    fundChange.setCurrentState(AuditState.DELETE);
                    fundChange.setCurrentAuditorId(user.getUserId());
                    fundChange.setLastAuditorId(user.getUserId());
//						fundChange.setLastDatetime(fund.);
                    fundChange.setCurrentDatetime(new Date());
                    fundChange.setSubmitNumber(fund.getSubmitNumber());

                    fundChange.setIsValid(true);

                }


                if (fundChangeMapper.insert(fundChange) > 0) {
                    logger.info("保存项目日志信息成功");
                } else {
                    logger.info("保存项目日志信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }
        fundEditorResult.setData(data);
        return fundEditorResult;


    }


    /**
     * 项目删除
     * 通过项目ID批量删除房屋信息， id以,号分割
     *
     * @param fundIdStr
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String fundIdStr, HttpServletResponse response) {
        String[] arr = fundIdStr.split(",");
        EditorResult<Fund> fundEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int fundId = Integer.valueOf(arr[i]);
            Fund fund = new Fund();
            fund.setIsDelete(1);
            fund.setPpId(fundId);
            if (fundMapper.updateByPrimaryKeySelective(fund) > 0) {
                System.out.println("删除" + fundId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return fundEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<Fund> pageDatatables(HttpServletRequest request, Fund fund) {
//		HttpSession httpSession = request.getSession();
//		User user = (User) httpSession.getAttribute("userInfo");
//		logger.info("用户信息：" + user.toString());
//		int community_id = user.getCommunity().getCommunityId();
//		fund.setCommunityId(community_id);

        List<Community> communities = communityMapper.findCommunitys();
        Options os = new Options();
        List<Option> optionList = new ArrayList<>();
        for (Community community : communities) {

            Option option = new Option();
            option.setLabel(community.getCommunityName());
            option.setValue(community.getCommunityId());
            optionList.add(option);


        }
        os.setCommunityId(optionList);
        List<Depart> departs = departMapper.findDeparts();
        optionList = new ArrayList<>();
        for (Depart depart : departs) {

            Option option = new Option();
            option.setLabel(depart.getDepartName());
            option.setValue(depart.getDepartId());
            optionList.add(option);


        }

        os.setDepartId(optionList);


        DataTablePageUtil<Fund> dataTable = new DataTablePageUtil<>(request);
        fund.setIsDelete(0);
        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Fund> list = fundMapper.selectSelective(fund);
        PageInfo<Fund> pageInfo = new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/fundComNotify")
    public DataTablePageUtil<Map> fundComNotify(HttpServletRequest request, Integer isOff) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String sql = "select p.*,c.community_name from tb_pp p,tb_community c where   " +
                "p.community_id = c.community_id " +
                " and p.is_delete=0 AND p.community_id =" + "'" + user.getCommunityId() + "'";
        if (null != isOff) {
            sql = sql + "  and  p.is_off =" + "'" + isOff + "'";
        }


        DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Map> list = this.getBySqlMapper.findRecords(sql);
        PageInfo<Map> pageInfo = new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        for (int i = 0; i < pageInfo.getList().size(); i++) {
            Map map = pageInfo.getList().get(i);
            String d = DateUtil.DATEtoString((Date) map.get("pp_date"), "yyyy-MM-dd");
            System.out.println(d);
            map.put("pp_date", d);


        }
        dataTable.setData(pageInfo.getList());
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/fundNotify")
    public DataTablePageUtil<Map> fundNotify(HttpServletRequest request) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        int userId = user.getUserId();
        String sql = "select p.*,c.community_name,u.real_name,pc.* from tb_pp_change pc,tb_user u,tb_pp p,tb_community c where   " +
                "u.user_id =pc.current_auditor_id and pc.pp_id=p.pp_id and u.community_id = c.community_id " +
                " and pc.is_valid =0 and p.is_delete=0 AND u.parent_id =" + "'" + userId + "'";


        DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Map> list = this.getBySqlMapper.findRecords(sql);
        PageInfo<Map> pageInfo = new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        for (int i = 0; i < pageInfo.getList().size(); i++) {
            Map map = pageInfo.getList().get(i);
            String d = DateUtil.DATEtoString((Date) map.get("pp_date"), "yyyy-MM-dd");
            System.out.println(d);
            map.put("pp_date", d);


        }
        dataTable.setData(pageInfo.getList());
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }


    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/changeDatatables")
    public DataTablePageUtil<Map> changeDatatables(HttpServletRequest request, Integer id) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");

        String sql = "select * from tb_pp_change,tb_user where tb_pp_change.current_auditor_id =tb_user.user_id and  pp_id=" + "'" + id + "'";

        DataTablePageUtil<Map> dataTable = new DataTablePageUtil<>(request);
        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Map> list = this.getBySqlMapper.findRecords(sql);
        PageInfo<Map> pageInfo = new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }


    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/fundEdit")
    public Object fundNotifyEdit(@RequestParam("id") String idStr, HttpServletRequest request, HttpServletResponse response) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");

        String[] arr = idStr.split(",");
        EditorResult<Map> fundEditorResult = new EditorResult<>();
        List<Map> data = new ArrayList<>();
        Fund fund = null;

        for (int i = 0; i < arr.length; i++) {
            int fundChangeId = Integer.valueOf(arr[i]);
            FundChange fundChange = fundChangeMapper.selectByPrimaryKey(fundChangeId);

            if (null == fundChange) {

                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                return null;
            }
            fund = fundMapper.selectByPrimaryKey(fundChange.getPpId());
            if (fund == null) {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                return null;
            }
            List<FieldError> fieldErrorList = new ArrayList<>();
            String prefix = "data[" + fundChangeId + "][";


            try {
                int currentState = Integer.valueOf(request.getParameter(prefix + "currentState]"));
                fundChange.setIsValid(true); //true代表这条记录的上级领导已经操作
                if (fundChangeMapper.updateByPrimaryKey(fundChange) > 0) {
                    logger.info("更新项目信息成功");
                } else {
                    logger.info("更新项目日志信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }

                FundChange fc = new FundChange();//产生新的修改日志
                fc.setPpId(fund.getPpId());
                fc.setCurrentState(currentState);
                fc.setCurrentAuditorId(user.getUserId());
                fc.setLastAuditorId(fundChange.getCurrentAuditorId());
                fc.setLastDatetime(fundChange.getCurrentDatetime());
                fc.setCurrentDatetime(new Date());
                fc.setSubmitNumber(fundChange.getSubmitNumber());
                fc.setIsValid(true);//直接返回，不再向上级申报
                String sql = "select current_auditor_id  from tb_pp_change where pp_id = " + fund.getPpId() + " and current_auditor_id !=" + user.getUserId() + "";
                List<Map> back_userIdMaps = this.getBySqlMapper.findRecords(sql);

                double amount = fundChangeMapper.getNewlyAmountById(fund.getPpId());
                if (currentState == 3) {//建议
                    String suggest = request.getParameter(prefix + "suggest]");
                    fc.setSuggest(suggest);
                    if (null != request.getParameter(prefix + "amount]") && !request.getParameter(prefix + "amount]").isEmpty()) {
                        amount = Double.valueOf(request.getParameter(prefix + "amount]"));
                    }
						/*else{
							fc.setAmount(fund.getAmount());
						}*/
					/*	fund.setIsOff(3);//建议



						for (Map back_userIdMap : back_userIdMaps) {
							sql = "insert into tb_back_notify (type_name,project_id,project_name,person_id,flag) values ('fund',"+fund.getPpId()+",'"+fund.getPpName()+"',"+back_userIdMap.get("current_auditor_id")+",3)";
							this.getBySqlMapper.insert(sql);

						}*/

                    if (user.getUserId() == user.getParentId()) {//同意，不存在上级领导
                        fund.setIsOff(7); //同意完成申报，社区未查看通知
                        fund.setAmount(amount);


                    } else {//同意，且存在上级领导

                        fc.setIsValid(false);//需要等待上级领导处理

                    }

                } else if (currentState == 1) {//同意 判定用户是否还有领导


                    if (user.getUserId() == user.getParentId()) {//同意，不存在上级领导
                        fund.setIsOff(7); //同意完成申报，社区未查看通知
                        fund.setAmount(amount);
                        fund.setBigAmount( NumberToCN.number2CNMontrayUnit(new BigDecimal(amount)));



                    } else {//同意，且存在上级领导

                        fc.setIsValid(false);//需要等待上级领导处理

                    }


                } else if (currentState == 2) {//拒绝

                    fund.setIsOff(2);
                    for (Map back_userIdMap : back_userIdMaps) {
                        sql = "insert into tb_back_notify (type_name,project_id,project_name,person_id,flag) values ('fund'," + fund.getPpId() + ",'" + fund.getPpName() + "'," + back_userIdMap.get("current_auditor_id") + ",2)";
                        this.getBySqlMapper.insert(sql);

                    }
                }

                fc.setAmount(amount);
                if (fundMapper.updateByPrimaryKeySelective(fund) > 0) {
                    logger.info("更新项目信息成功");
                } else {
                    logger.info("更新项目信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }
                if (fundChangeMapper.insertSelective(fc) > 0) {
                    logger.info("保存项目信息成功");
                } else {
                    logger.info("保存项目信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }


            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为整形");
                FieldError fieldError = new FieldError("amount", "格式不正确，必须为整型");
                fieldErrorList.add(fieldError);
            }
            if (fieldErrorList.size() > 0) {
                logger.error("字段错误");
                fundEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return fundEditorResult;
            }


            String sql = "select p.*,c.community_name,u.real_name,pc.* from tb_pp_change pc,tb_user u,tb_pp p,tb_community c where   " +
                    "u.user_id =pc.current_auditor_id and pc.pp_id=p.pp_id and u.community_id = c.community_id " +
                    "and pc.is_valid =0 AND  u.parent_id =" + "'" + user.getUserId() + "' and pc.pp_change_id =" + "'" + fundChangeId + "'";

            List<Map> list = this.getBySqlMapper.findRecords(sql);
            if (list.size() > 0) {
                data.add(list.get(0));
            }


        }
        fundEditorResult.setData(data);
        return fundEditorResult;


    }


    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/fundComEdit")
    public Object fundComNotifyEdit(@RequestParam("id") String idStr, HttpServletRequest request, HttpServletResponse response) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");

        String[] arr = idStr.split(",");
        EditorResult<Map> fundEditorResult = new EditorResult<>();
        List<Map> data = new ArrayList<>();
        Fund fund = null;

        for (int i = 0; i < arr.length; i++) {
            int fundId = Integer.valueOf(arr[i]);


            fund = fundMapper.selectByPrimaryKey(fundId);

            List<FieldError> fieldErrorList = new ArrayList<>();
            String prefix = "data[" + fundId + "][";

            if (null != request.getParameter(prefix + "is_off]")) {
                System.out.println("----------off");
                fund.setIsOff(1);
                if (fundMapper.updateByPrimaryKeySelective(fund) > 0) {
                    logger.info("更新项目信息成功");
                } else {
                    logger.info("更新项目信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }
            }

            String sql = "select p.*,c.community_name from tb_pp p,tb_community c where   " +
                    "p.community_id = c.community_id " +
                    " and p.is_delete=0  AND p.community_id =" + "'" + user.getCommunityId() + "'" +
                    " and p.pp_id =" + "'" + fundId + "'";

            List<Map> list = this.getBySqlMapper.findRecords(sql);
            if (list.size() > 0) {
                data.add(list.get(0));
            }


        }
        fundEditorResult.setData(data);
        return fundEditorResult;


    }

    private void getFund(HttpServletRequest request, String prefix, Fund fund, List<FieldError> fieldErrorList) {
        if (null != request.getParameter(prefix + "communityId]") && !request.getParameter(prefix + "communityId]").isEmpty()) {
            fund.setCommunityId(Integer.valueOf(request.getParameter(prefix + "communityId]")));


        }
        if (null != request.getParameter(prefix + "departId]") && !request.getParameter(prefix + "departId]").isEmpty()) {
            fund.setDepartId(Integer.valueOf(request.getParameter(prefix + "departId]")));


        }

        fund.setPpName(request.getParameter(prefix + "ppName]"));
        fund.setPpAdd(request.getParameter(prefix + "ppAdd]"));
        fund.setPpDetail(request.getParameter(prefix + "ppDetail]"));
        fund.setPeople(request.getParameter(prefix + "people]"));
        try {
            fund.setPpDate(DateUtil.StrToDate1(request.getParameter(prefix + "ppDate]")));
        } catch (Exception e) {
            logger.error("时间格式不正确，必须为YYYY-MM-DD");
            FieldError fieldError = new FieldError("amount", "时间格式不正确，必须为YYYY-MM-DD");
            fieldErrorList.add(fieldError);
        }
        try {
            fund.setAmount(Double.valueOf(request.getParameter(prefix + "amount]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为Double型");
            FieldError fieldError = new FieldError("amount", "格式不正确，必须为Double型");
            fieldErrorList.add(fieldError);
        }
        fund.setEventsOrg(request.getParameter(prefix + "eventsOrg]"));
        fund.setBudger(request.getParameter(prefix + "budger]"));


        if (null != request.getParameter(prefix + "isOff]") && !request.getParameter(prefix + "isOff]").isEmpty()) {
            try {
                fund.setIsOff(Integer.valueOf(request.getParameter(prefix + "isOff]")));
            } catch (NumberFormatException e) {
                logger.error("数量格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("isOff", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }

        }
        if (null != request.getParameter(prefix + "isDelete]") && !request.getParameter(prefix + "isDelete]").isEmpty()) {
            try {
                int isDelete = Integer.valueOf(request.getParameter(prefix + "isDelete]"));
                fund.setIsDelete(isDelete);
            } catch (NumberFormatException e) {
                logger.error("数量格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("isDelete", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }

        }
        if (null != request.getParameter(prefix + "submitNumber]") && !request.getParameter(prefix + "submitNumber]").isEmpty()) {
            try {
                fund.setSubmitNumber(Integer.valueOf(request.getParameter(prefix + "submitNumber]")));
            } catch (NumberFormatException e) {
                logger.error("数量格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("submitNumber", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }

        }


    }


}
